﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Text.Json; // 使用 System.Text.Json 解析 JSON

namespace Qwen_for_Windows.Model
{

    public class QwenModelChat
    {
        private static readonly HttpClient httpClient = new HttpClient();
        private List<Message> _conversationHistory = new List<Message>(); // 对话历史记录
        private const string SystemMessageContent = "You are a helpful assistant."; // 系统提示

        // 定义消息类
        private class Message
        {
            public string role { get; set; }
            public string content { get; set; }
        }

        public async Task<string> Single_Chat(string Question, string API_Key, string Model_Name, string Base_URL)
        {
            // 参数校验
            if (string.IsNullOrEmpty(Question)) return "请输入问题";
            if (string.IsNullOrEmpty(API_Key)) return "请输入API_Key\n请到阿里云百炼获取：https://bailian.console.aliyun.com/#/home";
            if (string.IsNullOrEmpty(Base_URL)) return "请输入Base_URL\n模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models";
            if (string.IsNullOrEmpty(Model_Name)) return "请输入模型名称\n模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models";

            // 1. 将用户的问题添加到对话历史中
            _conversationHistory.Add(new Message { role = "user", content = Question });

            // 2. 构造包含系统提示和历史消息的完整消息列表
            var messages = new List<Message>();
            messages.Add(new Message { role = "system", content = SystemMessageContent }); // 系统提示
            messages.AddRange(_conversationHistory); // 用户问题和之前的回答

            // 3. 生成请求的 JSON 内容
            var payload = new
            {
                model = Model_Name,
                messages = messages
            };
            string jsonContent = JsonSerializer.Serialize(payload);

            // 4. 发送请求并获取响应
            string responseContent = await SendPostRequestAsync(Base_URL, jsonContent, API_Key);

            // 5. 解析响应，提取回答内容并添加到历史记录中
            try
            {
                var jsonResponse = JsonSerializer.Deserialize<Dictionary<string, object>>(responseContent);
                var choices = (JsonElement)jsonResponse["choices"];
                var firstChoice = choices.EnumerateArray().First();
                var message = (JsonElement)firstChoice.GetProperty("message");
                string assistantResponse = message.GetProperty("content").GetString();

                // 将助手的回答添加到对话历史
                _conversationHistory.Add(new Message { role = "assistant", content = assistantResponse });

                return assistantResponse;
            }
            catch (Exception ex)
            {
                return $"解析响应失败: {ex.Message}\n原始响应: {responseContent}";
            }
        }

        private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
        {
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
            httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await httpClient.PostAsync(url, content);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                return $"请求失败: {response.StatusCode}";
            }
        }
    }
}
